import { Entity, Column, OneToMany, OneToOne, ManyToOne, JoinColumn } from "typeorm";

import {
  User,
  ENUM_USER,
  RefUserSub,
  UserEmail,
  UserEmailGateway,
  UserGateway,
  UserPassword,
  UserPasswordGateway,
  UserWeChat,
  UserWechatGateway,
  VARCHAR255_PG,
  VARCHAR50_PG,
  RefUserSubGateway,
} from "qqlx-core";

import {} from "@lib/orm.transfor.number";
import { TransformerVarchar255, TransformerVarchar50 } from "@lib/orm.transfor.string";
import { TransformerEnum } from "@lib/orm.transfor.enum";

import { JustUUidSchema } from "@/alpha/ext.uuid.base";
import { OwnerIdSchema } from "@/alpha/ext.id.base";

@Entity({ name: UserGateway.relations })
export class UserSchema extends JustUUidSchema implements User {
  @Column({ transformer: new TransformerVarchar50() })
  nickname: VARCHAR50_PG = "";

  @Column({ transformer: new TransformerVarchar255() })
  avatar: VARCHAR255_PG = "";

  @Column({ transformer: new TransformerVarchar50() })
  desc: VARCHAR50_PG = "";

  @Column({ transformer: new TransformerEnum(Object.values(ENUM_USER), ENUM_USER.NONE) })
  type: ENUM_USER = ENUM_USER.NONE;

  @OneToMany("RefUserSubSchema", (s: RefUserSub) => s.justCreator)
  joinRefUserSubList!: RefUserSub[];

  @OneToOne("UserEmailSchema", (s: UserEmail) => s.justOwner)
  justUserEmail!: UserEmail;

  @OneToOne("UserWeChatSchema", (s: UserWeChat) => s.justOwner)
  justUserWeChat!: UserWeChat;

  @OneToOne("UserPasswordSchema", (s: UserPassword) => s.justOwner)
  justUserPassword!: UserPassword;
}

@Entity({ name: RefUserSubGateway.relations })
export class RefUserSubSchema extends OwnerIdSchema implements RefUserSub {
  @Column({ transformer: new TransformerVarchar50() })
  refCreatorId!: VARCHAR50_PG;

  @ManyToOne("UserSchema", (s: User) => s.joinRefUserSubList)
  @JoinColumn({ name: "refCreatorId", referencedColumnName: "uuid32" })
  justCreator!: User;
}

// UserPassword
@Entity({ name: UserPasswordGateway.relations })
export class UserPasswordSchema extends OwnerIdSchema implements UserPassword {
  @Column({ transformer: new TransformerVarchar50() })
  accountNumber: VARCHAR50_PG = "";

  @Column({ transformer: new TransformerVarchar50() })
  password: VARCHAR255_PG = "";
}

@Entity({ name: UserEmailGateway.relations })
export class UserEmailSchema extends OwnerIdSchema implements UserEmail {
  @Column({ transformer: new TransformerVarchar50() })
  email: VARCHAR50_PG = "";
}

@Entity({ name: UserWechatGateway.relations })
export class UserWeChatSchema extends OwnerIdSchema implements UserWeChat {
  @Column({ transformer: new TransformerVarchar50() })
  unionId: VARCHAR50_PG = "";

  @Column({ transformer: new TransformerVarchar50() })
  nickname: VARCHAR50_PG = "";

  @Column({ transformer: new TransformerVarchar255() })
  avatar: VARCHAR255_PG = "";
}
